package com.household.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.household.domain.ResponseResult;
import com.household.domain.entity.Orders;
import com.household.domain.enums.OrderDeleteEnum;
import com.household.domain.enums.OrderStatusEnum;
import com.household.domain.enums.ResponseErrorCodeEnum;
import com.household.domain.enums.RoleEnum;
import com.household.domain.vo.AdminOrderVO;
import com.household.domain.vo.BootstrapTableVO;
import com.household.domain.vo.OrderDescVO;
import com.household.mapper.OrdersMapper;
import com.household.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created By wanzhen
 * 2023. 2023/4/4. 20:08
 */

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    private final OrdersMapper ordersMapper;
    @Autowired
    private DataSourceTransactionManager transactionManager;

    @Autowired
    public OrderServiceImpl(OrdersMapper ordersMapper) {
        this.ordersMapper = ordersMapper;
    }


    @Override
    public Map<String, Integer> getAdminDashboardData() {
        Map<String, Integer> map = new HashMap<>();
        List<Orders> list = ordersMapper.selectList(new QueryWrapper<Orders>().between("create_date", LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT), LocalDateTime.now()));
        Integer waitCount = Math.toIntExact(ordersMapper.selectCount(new QueryWrapper<Orders>().eq("state", OrderStatusEnum.WAIT_DIST.getStatus())));
        Integer transportCount = Math.toIntExact(ordersMapper.selectCount(new QueryWrapper<Orders>().eq("state", OrderStatusEnum.TRANSPORT.getStatus())));

        map.put("today", list.size());
        map.put("wait", waitCount);
        map.put("transport", transportCount);

        return map;


    }

    @Override
    public boolean isExistUnfinishedOrder(String userId) {
        int count = Integer.MAX_VALUE;
            count = ordersMapper.selectCount(new QueryWrapper<Orders>()
                    .eq("user_id", userId)
                    .in("status", OrderStatusEnum.WAIT_DIST.getStatus(), OrderStatusEnum.TRANSPORT.getStatus(),
                            OrderStatusEnum.COMPLETE.getStatus(),OrderStatusEnum.ERROR.getStatus()));


        return count != 0;
    }

    @Override
    public boolean isExist(String orderId) {
        return ordersMapper.selectById(orderId) != null;
    }

    @Override
    public BootstrapTableVO<AdminOrderVO> pageAdminOrderVO(Page<AdminOrderVO> page, String sql, int isDelete) {
        BootstrapTableVO<AdminOrderVO> vo = new BootstrapTableVO<>();
        IPage<AdminOrderVO> selectPage = ordersMapper.pageAdminOrderVO(page, sql, isDelete);

        vo.setTotal(selectPage.getTotal());
        vo.setRows(selectPage.getRecords());

        return vo;
    }


    @Override
    public ResponseResult batchRollback(String[] ids, String  userId) {
        int success = 0;
        for (String orderId : ids) {
            Orders order = ordersMapper.selectByIdIgnoreDelete(orderId);
            if (userId!=null&&userId.equals(order.getUserId())){
                continue;
            }

//            此处还原订单
            if (manualDelete(orderId,0, OrderDeleteEnum.CANCEL.getType())){
                success++;
            }
        }
        int finalSuccess=success;
        Map<String,Integer> count=new HashMap<String, Integer>(16){{
            put("success",finalSuccess);
            put("error",ids.length-finalSuccess);
        }};
        return ResponseResult.success(count);
    }

    @Override
    public boolean manualDelete(String  orderId, int hasDelete, int deleteType) {
        return ordersMapper.manualDelete(orderId,hasDelete,deleteType);
    }

    @Override
    public boolean isUserOrder(String orderId, String userId) {
        Orders info = getById(orderId);
        if(info == null) {
            return false;
        }
        return info.getUserId().equals(userId);
    }


    @Override
    public ResponseResult batchRemoveOrder(String[] ids) {
        int success = 0;
        for(String orderId : ids) {
            Orders orderInfo = ordersMapper.selectById(orderId);
//            if (orderInfo.getOrderStatus() == OrderStatusEnum.TRANSPORT) {
//                continue;
//            }
            if (orderInfo.getState() == OrderStatusEnum.TRANSPORT
                    || orderInfo.getState() == OrderStatusEnum.COMPLETE) {
                continue;
            }
            if(manualDelete(orderId, 1, OrderDeleteEnum.SYSTEM.getType())) {
                success++;
            }
        }

        Map<String, Integer> map = new HashMap<>();
        map.put("success", success);
        map.put("error", ids.length - success);

        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult batchDeleteOrder(String[] ids, String userId) {
        int success = 0;
        for(String orderId : ids) {
            Orders orderInfo = ordersMapper.selectById(orderId);
            if(!userId.equals(orderInfo.getUserId())) {
                continue;
            }
            if (orderInfo.getState() != OrderStatusEnum.COMPLETE && orderInfo.getState() != OrderStatusEnum.ERROR) {
                continue;
            }
            if(manualDelete(orderId, 1, OrderDeleteEnum.MANUAL.getType())) {
                success++;
            }
        }

        Map<String, Integer> map = new HashMap<>();
        map.put("success", success);
        map.put("error", ids.length - success);

        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult batchCancelOrder(String[] ids, String userId) {
        int success = 0;
        for(String orderId : ids) {
            Orders orderInfo = ordersMapper.selectById(orderId);
            if(!userId.equals(orderInfo.getUserId())) {
                continue;
            }
            if (orderInfo.getState() != OrderStatusEnum.WAIT_DIST) {
                continue;
            }
            if(manualDelete(orderId, 1, OrderDeleteEnum.CANCEL.getType())) {
                success++;
            }
        }
        int finalSuccess = success;
        Map<String, Integer> count = new HashMap<String, Integer>(16) {{
            put("success", finalSuccess);
            put("error", ids.length - finalSuccess);
        }};

        return ResponseResult.success(count);
    }




}
